#include <sys/time.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include<strings.h>
#include<ctype.h>
#include<errno.h>
#include<sys/wait.h>
#include<errno.h>
#include <time.h>
#define PORT 13330
#define BACKLOG 1
#define MAXRECVLEN 1024
int main(int argc, char *argv[])
{
    char buf[MAXRECVLEN];
    int listenfd, connectfd;  /* socket descriptors */
    pid_t pid; 
    pid_t pids[10]; 
    struct sockaddr_in server; /* server's address information */
    struct sockaddr_in client; /* client's address information */
    socklen_t addrlen;
    /* Create TCP socket */
    if ((listenfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
    {
        /* handle exception */
        perror("socket() error. Failed to initiate a socket");
        exit(1);
    }
 
    /* set socket option */
    int opt = SO_REUSEADDR;
    setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
    bzero(&server, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(PORT);
    server.sin_addr.s_addr = htonl(INADDR_ANY);
    if(bind(listenfd, (struct sockaddr *)&server, sizeof(server)) == -1)
    {
        /* handle exception */
        perror("Bind() error.");
        exit(1);
    }
    
    if(listen(listenfd, BACKLOG) == -1)
    {
        perror("listen() error. \n");
        exit(1);
    }
    addrlen = sizeof(client);
int i;
    for(i = 0; i< 10;i++){
        pid = fork();
        if(pid > 0){
            continue;
        }
        pids[i] = pid;
}
    while(1){
        if((connectfd=accept(listenfd,(struct sockaddr *)&client, &addrlen))==-1)
          {
            perror("accept() error. \n");
            exit(1);
          }
        struct timeval tv;
        gettimeofday(&tv, NULL);
    time_t t;
    t=time(NULL);
    printf("客户端IP: %s.  \n",inet_ntoa(client.sin_addr));
    printf("服务器实现者学号：%d\n",20155330);
    printf("当前时间: %s\n",ctime(&t));
    }    
        int iret=-1;
        while(1)
        {
            iret = recv(connectfd, buf, MAXRECVLEN, 0);
            if(iret>0)
            {
                //printf("%s\n", buf);
            }else
            {
                close(connectfd);
                break;
            }
            /* print client's ip and port */
            send(connectfd, buf, iret, 0); /* send to the client welcome message */
        }
    
    close(listenfd); /* close listenfd */
    return 0;
}
